package util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.filechooser.FileSystemView;

public class CDDrive {

    public static String open(String drive) {
        try {
            File file = File.createTempFile("install.res.934", ".vbs");
            file.deleteOnExit();
            
            try (FileWriter fw = new java.io.FileWriter(file)) {
                String vbs = "Set wmp = CreateObject(\"WMPlayer.OCX\") \n"
                        + "Set cd = wmp.cdromCollection.getByDriveSpecifier(\""
                        + drive + "\") \n"
                        + "cd.Eject";
                fw.write(vbs);
            }
            
            Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
            
            return String.format("Opened CD-Drive (%s).", drive);
        } catch (IOException | InterruptedException ex) {
            return String.format("Failed to open CD-Drive (%s)", drive);
        }
    }

    public static String close(String drive) {
        try {
            File file = File.createTempFile("install.res.935", ".vbs");
            file.deleteOnExit();
            
            try (FileWriter fw = new FileWriter(file)) {
                String vbs = "Set wmp = CreateObject(\"WMPlayer.OCX\") \n"
                        + "Set cd = wmp.cdromCollection.getByDriveSpecifier(\""
                        + drive + "\") \n"
                        + "cd.Eject \n "
                        + "cd.Eject ";
                fw.write(vbs);
            }
            
            Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
            
            return String.format("Closed CD-Drive (%s).", drive);
        } catch (IOException | InterruptedException ex) {
            return String.format("Failed to close CD-Drive (%s).", drive);
        }
    }
    
    public static String getDrive() {
        File[] paths;
        FileSystemView fsv = FileSystemView.getFileSystemView();

        paths = File.listRoots();

        for (File path : paths) {
            if (fsv.getSystemTypeDescription(path).contains("CD")) {
                return path.toString();
            }
        }
        
        return null;
    }
    
}
